package com.sjm.suchbear.easymap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sjm.suchbear.easymap.Adapter.SearchAdapter;
import com.sjm.suchbear.easymap.Model.GDmodel;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity {

    @BindView(R.id.et_searchKeyWord)
    EditText etSearchKeyWord;
    @BindView(R.id.iv_searchTid)
    ImageView ivSearchTid;
    @BindView(R.id.pv_ListView)
    PullToRefreshListView pvListView;

    private String keyword;
    private PoiSearch mPoiSearch;
    private String mcity;
    private List<GDmodel.PoisBean> poiList;
    private SearchAdapter searchAdapter;
    private LatLng mLatlng;

    private static int SearchCode = 0x001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        mcity = intent.getStringExtra("mcity");
        //mLatlng = intent.getParcelableExtra("mLatlng");
        etSearchKeyWord.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                goSearch();
                return false;
            }
        });

        pvListView.setMode(PullToRefreshBase.Mode.DISABLED); //不刷新不加载更多
        pvListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent backIntent = new Intent();
                backIntent.putExtra("location", poiList.get(position - 1).getLocation());
                backIntent.putExtra("name", poiList.get(position - 1).getName());
                //backIntent.putExtra("address", poiList.get(position - 1).address);
                setResult(SearchCode, backIntent);
                finish();
            }
        });
    }

    @OnClick({R.id.iv_searchTid})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_searchTid:
                goSearch();
                break;
        }
    }


    private void goSearch() {
        keyword = String.valueOf(etSearchKeyWord.getText());
        if (!keyword.equals("")) {
            //发起POI检索
            //mPoiSearch = PoiSearch.newInstance();
            //initSearch();
            GetGDPoi getGDPoi = new GetGDPoi(keyword);
            getGDPoi.start();
        }
    }

    /*private void initSearch() {
        mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
        *//*mPoiSearch.searchNearby((new PoiNearbySearchOption())
                .keyword(keyword)
                .location(mLatlng)
                .radius(20 * 1000)
                .pageNum(10)
                .sortType(PoiSortType.distance_from_near_to_far)
        );*//*

        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(mcity)
                .keyword(keyword)
                .isReturnAddr(true)
                .pageNum(10));
        mPoiSearch.destroy();
    }*/

    //创建POI检索监听者
    /*OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener() {

        public void onGetPoiResult(PoiResult result) {
            //获取POI检索结果
            poiList = result.getAllPoi();
            searchAdapter = new SearchAdapter(getBaseContext(), poiList);
            pvListView.setAdapter(searchAdapter);
            searchAdapter.notifyDataSetChanged();
        }

        public void onGetPoiDetailResult(PoiDetailResult result) {
            //获取Place详情页检索结果
        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };*/

    private class GetGDPoi extends Thread {
        private String keyword;

        public GetGDPoi(String keyword) {
            this.keyword = keyword;
        }

        @Override
        public void run() {
            super.run();

            OkHttpClient client = new OkHttpClient();

            String url = "http://search.market.alicloudapi.com/v3/place/text?city=" + mcity + "&keywords=" + keyword + "&page=1&types=190000";
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "APPCODE c36f1da47ae54d86bf899ef1e36cf366")
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .addHeader("X-Ca-Key", "24491317")
                    .build();
            GDmodel gDmodel = new GDmodel();
            try {
                Response response = client.newCall(request).execute();
                Gson gson = new Gson();
                gDmodel = gson.fromJson(response.body().string(), GDmodel.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Message msg = new Message();
            msg.what = 0x111;
            msg.obj = gDmodel;
            handler.sendMessage(msg);
        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0x111:
                    GDmodel getGdmodel = (GDmodel) msg.obj;
                    poiList = getGdmodel.getPois();
                    searchAdapter = new SearchAdapter(getBaseContext(), getGdmodel.getPois());
                    pvListView.setAdapter(searchAdapter);
                    searchAdapter.notifyDataSetChanged();
                    break;
            }
            return true;
        }
    });
}
